# Copyright (c) 2025, hzmes and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from frappe.utils import now, add_to_date, get_date_str, today, cstr


class HSFCertificationTask(Document):
	def before_insert(self):
		# 创建前自动查找供应商之联系人邮箱并赋值 self.email, 为定期邮件提醒提供收件人email
		supplier_doc = frappe.get_doc("SRM Supplier", self.supplier)
		if (len(supplier_doc.contactbackgroud) > 0) and supplier_doc.contactbackgroud[0].email_address:
			first_contact = supplier_doc.contactbackgroud[0]
			self.email = first_contact.email_address

	def validate(self):
		self.validate_duplicate_rows()
		
	def before_submit(self):
		self.validate_msds()
		self.validate_sub_status()
		# self.release_status = 'Yes'
		# self.save()
		# self.reload()

	# 提交后修改发布状态
	def on_submit(self):
		frappe.db.set_value(self.doctype, self.name, 'release_status', 'Yes')
		frappe.db.set_value("HSF Release Task Child", self.release_task_row, "release_status", "Finished")

	# 检验所有子页签是否已审核
	def validate_sub_status(self):
		if self.fmd_status != "Reviewed": frappe.throw("FMD状态未审核通过!")
		if self.msds_status != "Reviewed": frappe.throw("MSDS状态未审核通过!")
		if self.rohs_status != "Reviewed": frappe.throw("RoHS状态未审核通过!")
		if self.hf_status != "Reviewed": frappe.throw("HF状态未审核通过!")
		if self.reach_status != "Reviewed": frappe.throw("REACH状态未审核通过!")
		if self.others_status != "Reviewed": frappe.throw("其他资料状态未审核通过!")
		if self.special_status != "Reviewed": frappe.throw("特殊要求状态未审核通过!")
		if self.self_test_status != "Reviewed": frappe.throw("成品自测状态未审核通过!")

	# 检验原材料名称不允许重复
	def validate_duplicate_rows(self):
		seen = set()
		for row in self.get('hsf_fmd'):
			# 定义唯一键
			key = (row.raw_material_name, row.child_material_name)
			if key in seen:
				frappe.throw(f"发现重复行:原材料名称 {row.raw_material_name} 的 {row.child_material_name} 已存在")
			seen.add(key)

	# 校验MSDS附件是否上传完整
	def validate_msds(self):
		rows_idx = []
		for row in self.get('msds'):
			if not row.msds and not row.ip_from and not row.patent:
				rows_idx.append(row.idx)
		if len(rows_idx) > 0:
			rows = ','.join(frappe.utils.cstr(p) for p in rows_idx )
			frappe.throw(f"MSDS页签校验Error, 行次: {rows} 不满足MSDS,IP Form和Paten三者必有其一")

	@frappe.whitelist()
	def copy_from_fmd(self, subtable):
		if self.get(f"{subtable}"):
			for item in self.get('hsf_fmd'):
				if item.raw_material_name in self.get(f"{subtable}"):
					pass
				else:
					self.append(f"{subtable}", {"raw_material_name": item.raw_material_name, "manufacturer_material": item.manufacturer_material})
		else:
			for item in self.get('hsf_fmd'):
				self.append(f"{subtable}", {"raw_material_name": item.raw_material_name, "manufacturer_material": item.manufacturer_material})
		self.save()
		self.reload()

	# 校验: 如果上传了附件, 则报告编号\报告日期\检测机构要求必填
	def validate_reports(self):
		voilations = []
		for item in self.get('rohs'):
			pass
			# if item.
		for item in self.get('hf'):
			pass
		for item in self.get('reach'):
			pass
		for item in self.egt('others'):
			pass